﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EquipmentManager.Properties;
using EquipmentManager.Dtos;
using System.Threading;
using ServiceStack;

namespace EquipmentManager.Services
{

    public class Session
    {
        public string UserName { get; set; }
        public DateTime LastVisitTime { get; set; }
        public int MinutesOfTimeout { get; set; }
        public string SessionID { get; set; }

    }
    public static class RequestLoginValidateTools
    {
        private static int _LogoutCheckPeriod = Settings.Default.LogoutCheckPeriod; //设置检查用户登陆超时的间隔，默认为1分钟
        private static List<Session> LogedSessions;
        //private static ILog log;
        static RequestLoginValidateTools()
        {
            //log = LogManager.GetLogger(Settings1.Default.UserLoginUsingLogger);
            LogedSessions = new List<Session>();
            Timer timer = new Timer(LoginTimeOutCheckRoutine, null, _LogoutCheckPeriod, _LogoutCheckPeriod);
        }
        //定时检查登录是否超时
        private static void LoginTimeOutCheckRoutine(Object obj)
        {
            lock (LogedSessions)
            {
                LogedSessions.RemoveAll(p => {
                    if (p.MinutesOfTimeout == 0) //Timeout=0 为永不超时
                        return false;
                    if (p.LastVisitTime.AddMinutes(p.MinutesOfTimeout) < DateTime.Now)
                    {
                        //log.InfoFormat("后台超时注销了{0}", p.User);
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }); //删除超时的
            }
        }
        private static Session FindSession(string sid)
        {
            Session res = null;
            lock (LogedSessions)
            {
                res = LogedSessions.Find(x => x.SessionID == sid);
                if (res != null)
                    res.LastVisitTime = DateTime.Now; //更新最后访问时间
            }
            return res;
        }
        private static void CheckLogin(string sid)
        {
            if (FindSession(sid) == null)
                throw HttpError.Unauthorized("未登录或登陆超时，请重新登陆。");
        }
        private static bool Logout(string sid)
        {
            int count = 0;
            lock (LogedSessions)
            {
                count = LogedSessions.RemoveAll(p => p.SessionID == sid);
            }
            if (count == 0)
                return false;
            else
                return true;
            //log.InfoFormat("准备注销{0}，实际注销{1}个用户.", dto.SessionID, count);
        }

        public static String Login(string username, int timeout)
        {
            Session sec = new Session() {
                SessionID = Guid.NewGuid().ToString(),
                LastVisitTime = DateTime.Now,
                UserName = username,
                MinutesOfTimeout = timeout
            };
            lock (LogedSessions)
            {
                LogedSessions.Add(sec);
            }
            //log.InfoFormat("登陆了一个用户, 用户名：{0}", sec.User);
            return sec.SessionID;
        }

        public static bool Logout(ServiceStack.Web.IRequest request)
        {
            if (request.Cookies.ContainsKey(Settings.Default.SessionCookieName))
                return Logout(request.Cookies[Settings.Default.SessionCookieName].Value);
            else
                return false;
        }

        public static Session CheckLogin(ServiceStack.Web.IRequest request)
        {
            if (request.Cookies.ContainsKey(Settings.Default.SessionCookieName))
            {
                Session res = FindSession(request.Cookies[Settings.Default.SessionCookieName].Value);
                if (res == null)
                    throw HttpError.Unauthorized("登陆超时，请重新登陆。");
                else
                    return res;
            }
            else
                throw HttpError.Unauthorized("请登陆!");

        }
    }
}
